package com.bzyd.ss.encoder;

import org.springframework.security.crypto.password.PasswordEncoder;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * MD5加密器
 */
public class MD5PasswordEncoder implements PasswordEncoder {
    @Override
    public String encode(CharSequence charSequence) {
        try {
            MessageDigest digest = MessageDigest.getInstance("MD5");
            byte[] tmp = digest.digest(charSequence.toString().getBytes(StandardCharsets.UTF_8));
            return toHexString(tmp);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return "";
        }
    }

    @Override
    public boolean matches(CharSequence charSequence, String s) {
        return s.equals(encode(charSequence));
    }

    private String toHexString(byte[] tmp){
        //把字节以16进制的方式显示
        StringBuilder builder = new StringBuilder("");
        for (int i = 0; i < tmp.length; i++) {
            String s = Integer.toHexString(tmp[i] & 0xFF);
            if (s.length() == 1) {
                builder.append("0");
            }
            builder.append(s);
        }
        return builder.toString();
    }
}
